package com.zkhz.base.common.dto;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.springframework.lang.NonNull;

import java.util.Collections;
import java.util.List;

/**
 *
 * @author wuzeqin
 * @date 2020/5/18
 **/
@ApiModel("分页查询结果")
@Data
public class PageResultDTO<T>  {

    @ApiModelProperty(value = "页码", example = "1")
    private long pageNum;

    @ApiModelProperty(value = "每页记录", example = "10")
    private long pageSize;

    @ApiModelProperty(value = "总的记录数", example = "23")
    private long total;

    @ApiModelProperty(value = "总页数", example = "6")
    private long totalPages;

    @NonNull
    @ApiModelProperty(value = "结果数据列表")
    private List<T> data;

    private PageResultDTO(){
        this.pageNum = 1;
        this.pageSize = 10;
        this.total = 0;
        this.totalPages = 0;
        this.data = Collections.emptyList();
    }

    //use PaginationResultDTO.of(data)
    private PageResultDTO(List<T> data) {
        this.data = data;
        this.pageNum = 1;
        this.pageSize = data.size();
        this.total = data.size();
        this.totalPages = 1;
    }

    //use PaginationResultDTO.of(page)
    private PageResultDTO(Page<T> page) {
        this.pageNum = page.getCurrent();
        this.pageSize = page.getSize();
        this.total = page.getTotal();
        this.data = page.getRecords();
        this.totalPages = page.getPages();
    }

    /**
     * @deprecated use {@link #getPageNum()}。兼容旧的，新的统一用getPageNum。
     */
    @Deprecated
    @ApiModelProperty(position = 999, value = "旧的页码（兼容旧的对接，现在统一用pageNum）")
    public long getPage() {
        return pageNum;
    }

    public static <T> PageResultDTO<T> of(List<T> data) {
        return new PageResultDTO<>(data);
    }

    public static <T> PageResultDTO<T> of(Page<T> page) {
        return new PageResultDTO<>(page);
    }

    public static <T> PageResultDTO<T> of(PageResultDTO<?> other, List<T> data) {
        PageResultDTO<T> result = new PageResultDTO<>();
        result.pageNum = other.getPageNum();
        result.pageSize = other.getPageSize();
        result.total = other.getTotal();
        result.data = data;
        result.totalPages = other.getTotalPages();
        return result;
    }
}
